package com.ruicar.afs.cloud.channel.common.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.admin.api.dto.UserSimpleInfoDto;
import com.ruicar.afs.cloud.admin.api.feign.AfsUserFeign;
import com.ruicar.afs.cloud.channel.cardealer.condition.CarDealerCondition;
import com.ruicar.afs.cloud.channel.cardealer.condition.DirectCarDealerCondition;
import com.ruicar.afs.cloud.channel.common.condition.*;
import com.ruicar.afs.cloud.channel.common.entity.CarToList;
import com.ruicar.afs.cloud.channel.common.feign.ChannelUseApplyService;
import com.ruicar.afs.cloud.channel.common.feign.ChannelUseCaseService;
import com.ruicar.afs.cloud.channel.common.mq.sender.SenderChannelToApply;
import com.ruicar.afs.cloud.channel.common.mq.sender.SenderChannelToCase;
import com.ruicar.afs.cloud.channel.common.mq.sender.config.ArchiveConfig;
import com.ruicar.afs.cloud.channel.common.mq.sender.config.CommissionConfig;
import com.ruicar.afs.cloud.channel.common.mq.sender.impl.ChannelIdToCommissionSystemImpl;
import com.ruicar.afs.cloud.channel.common.mq.sender.impl.SenderChannelToApplyImpl;
import com.ruicar.afs.cloud.channel.common.mq.sender.impl.SenderChannelToArchiveImpl;
import com.ruicar.afs.cloud.channel.common.mq.sender.impl.SenderChannelToCaseImpl;
import com.ruicar.afs.cloud.channel.common.until.ChannelConfig;
import com.ruicar.afs.cloud.channel.online.condition.ChannelUserCondition;
import com.ruicar.afs.cloud.channel.online.service.ChannelOnlineService;
import com.ruicar.afs.cloud.channel.witness.entity.ChannelWitnessInfoTemp;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.mq.rabbit.message.AfsTransEntity;
import com.ruicar.afs.cloud.common.mq.rabbit.message.MqTransCode;
import com.ruicar.afs.cloud.image.config.GwtFastdfsProperties;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.entity.ComAttachmentManagement;
import com.ruicar.afs.cloud.image.enums.AttachmentClassEnum;
import com.ruicar.afs.cloud.image.service.ComAttaManageService;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import com.ruicar.afs.cloud.image.service.ComAttachmentManagementService;
import com.ruicar.afs.cloud.image.store.enums.IsViewEnum;
import com.ruicar.afs.cloud.image.vo.AttachmentDataSendVo;
import com.ruicar.afs.cloud.parameter.commom.entity.TsysVehicleDetail;
import com.ruicar.afs.cloud.parameter.commom.entity.TsysVehicleModel;
import com.ruicar.afs.cloud.parameter.commom.entity.VeBrand;
import com.ruicar.afs.cloud.parameter.commom.entity.VeMain;
import com.ruicar.afs.cloud.parameter.commom.service.TsysVehicleDetailService;
import com.ruicar.afs.cloud.parameter.commom.service.TsysVehicleModelService;
import com.ruicar.afs.cloud.parameter.commom.vo.VeBrandVo;
import com.ruicar.afs.cloud.parameter.commom.vo.VeMainVo;
import com.ruicar.afs.cloud.vehicle.dto.CarInfoDto;
import com.ruicar.afs.cloud.vehicle.feign.VehicleApiFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jdk.nashorn.internal.objects.annotations.Getter;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.net.URI;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author Ice
 * @Date 2020/6/9
 */
@RestController
@AllArgsConstructor
@Api("通用接口")
@RequestMapping("/common")
public class CommonController {
    private ChannelConfig channelConfig;
    private ChannelUseApplyService channelUseApplyService;
    private ChannelUseCaseService channelUseCaseService;
    private VehicleApiFeign vehicleApiFeign;
    private ChannelOnlineService channelOnlineService;
    private final AfsUserFeign afsUserFeign;
    private TsysVehicleModelService tsysVehicleModelService;
    private final SenderChannelToCaseImpl senderChannelToCaseImpl;
    private final SenderChannelToApplyImpl senderChannelToApplyImpl;
    private final SenderChannelToCase senderChannelToCase;
    private final SenderChannelToApply senderChannelToApply;

    private GwtFastdfsProperties gwtFastdfsProperties;
    private ComAttachmentFileService comAttachmentFileService;
    private final TsysVehicleDetailService tsysVehicleDetailService;

    private ChannelIdToCommissionSystemImpl channelIdToCommissionSystem;

    private final SenderChannelToArchiveImpl senderChannelToArchive;
    private final ComAttaManageService comAttaManageService;

//    private SysRoleService sysRoleService;
//    private SysUserRoleService userRoleService;
//    private SysUserService userService;


    @PostMapping(value = "/getCaseSave")
    @ApiOperation(value = "见证人保存或修改到案件")
    public IResponse getCaseSave(@RequestBody ChannelWitnessInfoTemp condition) {

        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
        return channelUseCaseService.getCaseSave(condition, headers);
    }

    @PostMapping(value = "/upDateCaseStatusByIds/{ids}")
    @ApiOperation(value = "根据id停用挂靠公司")
    public JSONObject upDateCaseStatusByIds(@PathVariable(value = "ids") String ids) {
        //截取字符串
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
        return channelUseCaseService.upDateCaseStatusByIds(ids, headers);
    }

    @PostMapping(value = "/upDateCaseStatusByIdsForApply")
    @ApiOperation(value = "根据id停用挂靠公司")
    public JSONObject upDateCaseStatusByIdsForApply(@RequestBody String ids) {
        //截取字符串
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
        return channelUseCaseService.upDateCaseStatusByIdsForApply(ids, headers);
    }

    @PostMapping(value = "/saveThirdOrNetCar")
    @ApiOperation(value = "同步案件数据")
    public IResponse saveThirdOrNetCar(@Valid @RequestBody ChannelAffiliatedToCaseCondition channelAffiliatedCondition) {
        //截取字符串
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
        return channelUseCaseService.saveThirdOrNetCar(channelAffiliatedCondition, headers);
    }

    @PostMapping(value = "/getCarByVin")
    @ApiOperation(value = "通过VIN号获取车辆信息")
    public IResponse getCarByVin(@RequestBody CarInfoDto dto) {
        return new IResponse().setData(vehicleApiFeign.newCarKeyParameters(dto));
    }

    @PostMapping(value = "/getCarTree")
    @ApiOperation(value = "品牌树")
    public IResponse getCarTree(@RequestBody VehicleCondition condition) {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getApplyClientId());
        headers.put("clientSecret", channelConfig.getApplyClientSecret());
        return channelUseApplyService.getCarTree(condition, headers);
    }

    @PostMapping(value = "/getDeptInfo/{channelId}/{parentId}")
    @ApiOperation(value = "部门树")
    public IResponse getDeptInfo(@PathVariable(value = "channelId") String channelId, @PathVariable(value = "parentId") String parentId) {
        return channelOnlineService.getDeptInfo(channelId, parentId);
    }

    @PostMapping(value = "/resetPassword/{id}")
    @ApiOperation(value = "密码重置")
    public IResponse resetPassword(@PathVariable(value = "id") Long id) {
        return channelOnlineService.resetPassword(id);
    }

    @PostMapping("/addCommonCarDealer")
    @ApiOperation(value = "增加普通车商到案件服务")
    public IResponse addCarDealer(@RequestBody CarDealerCondition condition) {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
        return channelUseCaseService.addCarDealer(condition, headers);
    }

    @RequestMapping(value = "/saveDirectCarDealer", method = RequestMethod.POST)
    @ApiOperation(value = "保存直营车商申请信息到案件服务")
    public IResponse saveDirectCarDealer(@RequestBody DirectCarDealerCondition condition) {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
        return channelUseCaseService.saveDirectCarDealer(condition, headers);
    }


    @PostMapping("/savaInvoiceInfo")
    @ApiOperation(value = "保存开票信息到案件服务")
    public IResponse savaInvoiceInfo(@RequestBody DirectCarDealerCondition condition) {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
        return channelUseCaseService.savaInvoiceInfo(condition, headers);
    }

    @GetMapping("/disableCarDealerFromCase/{ids}")
    @ApiOperation(value = "禁用案件服务中普通车商")
    public IResponse diableCarDealer(@PathVariable String[] ids) {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
        return channelUseCaseService.diableCarDealer(ids, headers);
    }

    @GetMapping("/disableDirectCarDealerFromCase/{ids}")
    @ApiOperation(value = "禁用案件服务中直营车商")
    public IResponse disableDirectCarDealer(@PathVariable String[] ids) {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
        return channelUseCaseService.disableDirectCarDealer(ids, headers);
    }

    @PostMapping(value = "/getBaseInfo")
    @ApiOperation(value = "获取合作商")
    public IResponse getBaseInfo(@RequestBody StatusCondition statusCondition) {
        //截取字符串
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
        return channelUseCaseService.getBaseInfo(statusCondition, headers);
    }


    @GetMapping("/bulkEditingSalesmanFromCase/{salesman}/{ids}")
    @ApiOperation(value = "批量修改业务员")
    public IResponse bulkEditingSalesman(@PathVariable String salesman, @PathVariable String[] ids) {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
        return channelUseCaseService.bulkEditingSalesman(salesman, ids, headers);
    }


    @PostMapping(value = "/getBaseInfoPage")
    @ApiOperation(value = "分页获取合作商")
    public IResponse getBaseInfoPage(@RequestBody StatusCondition statusCondition) {
        //截取字符串
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
        return channelUseCaseService.getBaseInfoPage(statusCondition, headers);
    }


    @PostMapping(value = "/getUserInfo")
    @ApiOperation(value = "获取用户信息")
    public IResponse getUserInfo(@RequestBody ChannelUserCondition condition) {
        return channelOnlineService.getUserInfo(condition);
    }

    @PostMapping(value = "/getStopNewApply")
    @ApiOperation(value = "获取这个合作商下面被停的新车进件")
    public IResponse getStopNewApply(@RequestBody ChannelUserCondition condition) {
        return channelOnlineService.getStopNewApply(condition);
    }

    @PostMapping(value = "/获取这个合作商下面被停的二手车进件")
    @ApiOperation(value = "获取用户信息")
    public IResponse getStopOldApply(@RequestBody ChannelUserCondition condition) {
        return channelOnlineService.getStopOldApply(condition);
    }

    @PostMapping(value = "/获取这个合作商下面被停的新车账户")
    @ApiOperation(value = "获取用户信息")
    public IResponse getStopNewUser(@RequestBody ChannelUserCondition condition) {
        return channelOnlineService.getStopNewUser(condition);
    }

    @PostMapping(value = "/getStopOldUser")
    @ApiOperation(value = "获取这个合作商下面被停的二手车账户")
    public IResponse getStopOldUser(@RequestBody ChannelUserCondition condition) {
        return channelOnlineService.getStopOldUser(condition);
    }

    @PostMapping(value = "/getAllByPage")
    @ApiOperation(value = "获取所有角色")
    public IResponse getAllByPage(@RequestBody ChannelUserCondition condition) {
        return channelOnlineService.getAllByPage(condition.getPageNumber(), condition.getPageSize(),condition.getRoleType());
    }

    @GetMapping("/getAllRegionalManager/{role}")
    @ApiOperation(value = "根据角色code获取所有用户")
    public IResponse getAllSaleManByChannelId(@PathVariable String role) {
        IResponse<List<UserSimpleInfoDto>> listIResponse = afsUserFeign.getSimpleUserListByRoleCode(role);
        return IResponse.success(listIResponse);
    }

    @PostMapping(value = "/getBaseInfoByType")
    @ApiOperation(value = "根据合作商类型查询全部")
    public IResponse getBaseInfoByType(@RequestBody BaseInfoTypeDTO dto) {
        //截取字符串
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
        return channelUseCaseService.getBaseInfoByType(dto, headers);
    }

    @PostMapping(value = "/getBaseInfoByRole")
    @ApiOperation(value = "根据角色属性查询渠道信息")
    public IResponse getBaseInfoByRole(@RequestBody BaseInfoTypeDTO dto) {
        //截取字符串
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
        return channelUseCaseService.getBaseInfoByRole(dto, headers);
    }


    @PostMapping(value = "/stopApply")
    @ApiOperation(value = "停新车二手车进件")
    public IResponse stopApply(@RequestBody StartOrStopDTO condition) {
        return channelOnlineService.stopApply(condition);
    }

    @PostMapping(value = "/startApply")
    @ApiOperation(value = "启新车二手车进件")
    public IResponse startApply(@RequestBody StartOrStopDTO condition) {
        return channelOnlineService.startApply(condition);
    }


    @PostMapping(value = "/stopUser")
    @ApiOperation(value = "停新车二手车账户")
    public IResponse stopUser(@RequestBody StartOrStopDTO condition) {
        return channelOnlineService.stopUser(condition);
    }

    @PostMapping(value = "/startUser")
    @ApiOperation(value = "启新车二手车账户")
    public IResponse startUser(@RequestBody StartOrStopDTO condition) {
        return channelOnlineService.startUser(condition);
    }

    @PostMapping(value = "/synchro")
    @ApiOperation(value = "同步车型库数据")
    @Transactional
    public IResponse synchro() throws ParseException {
        // 查询车型库最新的时间
        List<TsysVehicleDetail> details = tsysVehicleDetailService.list(Wrappers.<TsysVehicleDetail>query().lambda().orderByDesc(TsysVehicleDetail::getUpdateTime));
        if(details.size()<=0){
            throw new AfsBaseException("系统暂无车型库数据！");
        }
        CarInfoDto dto = new CarInfoDto();
        dto.setVersion(details.get(0).getUpdateTime().getTime());
        JSONObject json= vehicleApiFeign.brandAndCode(dto);
        if("0".equals(json.get("code").toString())){
            JSONObject data = json.getJSONObject("data");
            List<VeBrand> veBrand = data.getJSONArray("veBrandList").toJavaList(VeBrand.class);
            List<VeMain> veMain = data.getJSONArray("veMainList").toJavaList(VeMain.class);
            // 说明返回成功
            if (veBrand.size()>0||veMain.size()>0){
                //  同步自己的数据
                this.synchroVehicle(veBrand,veMain);
                // 同步到进件

                if(veBrand.size()>0){
                    VeBrandVo brandVo=new VeBrandVo();
                    brandVo.setVeBrandList(veBrand);
                    AfsTransEntity<VeBrandVo> transEntity = new AfsTransEntity();
                    transEntity.setTransCode(MqTransCode.CHANNEL_CHANNEL_APPLY_POS_SEND_VEHICLE_BRAND_APPLY);
                    transEntity.setData(brandVo);
                    senderChannelToApply.sendSynchroBrand(transEntity);
                }
                if(veMain.size()>0){
                    VeMainVo mainVo=new VeMainVo();
                    mainVo.setVeMainList(veMain);
                    AfsTransEntity<VeMainVo> transEntity = new AfsTransEntity();
                    transEntity.setTransCode(MqTransCode.CHANNEL_CHANNEL_APPLY_POS_SEND_VEHICLE_MAIN_APPLY);
                    transEntity.setData(mainVo);
                    senderChannelToApply.sendSynchroMain(transEntity);
                }

                // 同步到案件
//                AfsTransEntity<List<VeBrand>> transBrandCase =senderChannelToCaseImpl.sendVeBrand(veBrand);
//                AfsTransEntity<List<VeMain>> transMainCase =senderChannelToCaseImpl.sendVeMain(veMain);
//                senderChannelToCase.sendSynchroBrand(transBrandCase);
//                senderChannelToCase.sendSynchroMain(transMainCase);

            }
        }else {
            throw new AfsBaseException("获取车型库信息失败！");
        }
        return IResponse.success("同步成功！");
    }

    @PostMapping(value = "/getChannelSeal")
    @ApiOperation(value = "通过渠道id 获取渠道的印章")
    public IResponse<List<ComAttachmentFile>> getChannelSeal(@RequestBody String channelId){
        // 写死的一个印章 专属 唯一值 SealExclusive
        ComAttachmentManagement comAttachmentManagement=comAttaManageService.getOne(Wrappers.<ComAttachmentManagement>query().lambda().eq(ComAttachmentManagement::getUniqueCode,"SealExclusive"));
        List<ComAttachmentFile> fileList = comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                    .eq(ComAttachmentFile::getAttachmentCode, comAttachmentManagement.getId().toString())
                    .eq(ComAttachmentFile::getBusiNo, channelId)
                    .eq(ComAttachmentFile::getBelongNo, channelId)
                    .eq(ComAttachmentFile::getHistoryVersion, "0"));//获取当前最新的附件，不获取历史版本。

        return IResponse.success(fileList);
    }

    public void synchroVehicle(List<VeBrand> brands, List<VeMain> mains) throws ParseException {
        DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(brands.size()>0){
            for (VeBrand brand:brands){
                TsysVehicleModel model = tsysVehicleModelService.getOne(Wrappers.<TsysVehicleModel>query().lambda()
                        .eq(TsysVehicleModel::getCode,brand.getCode()));
                if(model==null){
                    // 说明没有 我要去添加
                    TsysVehicleModel m=new TsysVehicleModel();
                    m.setCode(brand.getCode());
                    m.setModels(brand.getBrand());
                    m.setBrandCode(brand.getMaker());
                    if(brand.getOrderid()!=null&&brand.getOrderid()!=""){
                        m.setOrderId(Integer.valueOf(brand.getOrderid()));
                    }
                    m.setIsActive(brand.getIsactive());
                    m.setStyleRule(brand.getStylerule());
                    m.setFullName(brand.getFullname());
                    m.setCmsId(brand.getCmsid());
                    m.setType(brand.getType());
                    m.setSeriesId(brand.getSeriesid());
                    m.setAdditionalTag(brand.getAdditionaltag());
                    m.setNeedSync(brand.getNeedsync());
                    m.setCreateBy(brand.getCreateuser());
                    m.setUpdateBy(brand.getUpdateuser());
                    m.setDelFlag(brand.getIsdelete());
                    m.setCreateTime(new Date(System.currentTimeMillis()));
                    m.setUpdateTime(new Date(System.currentTimeMillis()) );
                    tsysVehicleModelService.save(m);

                    // 去同步佣金
                    String ss= channelIdToCommissionSystem.AssembledVehicleType(brand.getBrand(),brand.getCode(),brand.getType(),brand.getFullname());
                    channelIdToCommissionSystem.sendAlterDealerMq(m.getId().toString(),CommissionConfig.TABLECODE_VEBRAND,CommissionConfig.ACTION_ADD,ss);
                }else {
                    // 说明存在去更新
                    model.setCode(brand.getCode());
                    model.setModels(brand.getModels());
                    model.setBrandCode(brand.getMaker());
                    if(brand.getOrderid()!=null&&brand.getOrderid()!=""){

                        model.setOrderId(Integer.valueOf(brand.getOrderid()));
                    }
                    model.setIsActive(brand.getIsactive());
                    model.setStyleRule(brand.getStylerule());
                    model.setFullName(brand.getFullname());
                    model.setCmsId(brand.getCmsid());
                    model.setType(brand.getType());
                    model.setSeriesId(brand.getSeriesid());
                    model.setAdditionalTag(brand.getAdditionaltag());
                    model.setNeedSync(brand.getNeedsync());
                    model.setCreateBy(brand.getCreateuser());
                    model.setUpdateBy(brand.getUpdateuser());
                    model.setDelFlag(brand.getIsdelete());
                    model.setUpdateTime(new Date(System.currentTimeMillis()));
                    tsysVehicleModelService.updateById(model);

                    String ss= channelIdToCommissionSystem.AssembledVehicleType(brand.getBrand(),brand.getCode(),brand.getType(),brand.getFullname());
                    channelIdToCommissionSystem.sendAlterDealerMq(model.getId().toString(),CommissionConfig.TABLECODE_VEBRAND,CommissionConfig.ACTION_EDIT,ss);
                }
            }
        }
        if(mains.size()>0){
            for (VeMain main:mains){
                TsysVehicleDetail detail =tsysVehicleDetailService.getOne(Wrappers.<TsysVehicleDetail>query().lambda()
                        .eq(TsysVehicleDetail::getCode,main.getCode()).eq(TsysVehicleDetail::getModelCode,main.getBrandcode()));
                if(detail==null){
                    TsysVehicleDetail t =new TsysVehicleDetail();
                    t.setModelCode(main.getBrandcode());
                    t.setCode(main.getCode());
                    t.setName(main.getName());
                    if(main.getGuideprice()!=null){
                        t.setGuidePrice(new BigDecimal(main.getGuideprice()));
                    }
                    t.setIsActive(main.getIsactive());
                    if(main.getOrderid()!=null&&main.getOrderid()!=""){
                        t.setOrderId(Integer.valueOf(main.getOrderid()));
                    }
                    t.setDisplacement(main.getVehiclemain05());
                    t.setTransmission(main.getVehiclemain06());
                    t.setConfigure(main.getVehiclemain07());
                    t.setYearStyle(main.getYearstyle());
                    t.setAssetsCode(main.getZichancode());
                    t.setPowerType(main.getDonglitype());
                    t.setDriver(main.getDriver());
                    t.setBlowoff(main.getPaifang());
                    t.setCmsId(main.getCmsid());
                    t.setRedBlue(main.getVemain01());
                    t.setMemo(main.getMemo());
                    t.setInterior(main.getVemain02());
                    t.setModelId(main.getModelid());
                    t.setChe300Style(main.getChe300style());
                    if(main.getChelong()!=null){
                        t.setCarLength(new BigDecimal(main.getChelong()));
                    }
                    if(main.getWight()!=null){
                        t.setWight(new BigDecimal(main.getWight()));
                    }
                    if(main.getSeatnum()!=null){
                        t.setSeatNum(new BigDecimal(main.getSeatnum()));
                    }
                    t.setCarLevel(main.getCarlevel());
                    t.setIsParallel(main.getIsparallel());
                    t.setNeedSync(main.getNeedsync());
                    t.setIsInternet(main.getIschelianwag());
                    t.setIsGreen(main.getIsgreen());
                    t.setCarType(main.getCartype());
                    t.setCarTypeDetail(main.getCartypedetail());
                    t.setUpdateTime(fmt.parse(main.getUpdatedate()));
                    t.setUpdateBy(main.getUpdateuser());
                    t.setCreateBy(main.getCreateuser());
                    t.setCreateTime(new Date(System.currentTimeMillis()));
                    t.setUpdateTime(new Date(System.currentTimeMillis()));
                    tsysVehicleDetailService.save(t);
                    // 同步到佣金
                    String ss= channelIdToCommissionSystem.AssemblyModelData(t.getName(),t.getCode());
                    channelIdToCommissionSystem.sendAlterDealerMq(t.getId().toString(),CommissionConfig.TABLECODE_SSCODE,CommissionConfig.ACTION_ADD,ss);
                }else {
                    detail.setModelCode(main.getBrandcode());
                    detail.setCode(main.getCode());
                    detail.setName(main.getName());
                    if(main.getGuideprice()!=null){
                        detail.setGuidePrice(new BigDecimal(main.getGuideprice()));
                    }
                    detail.setIsActive(main.getIsactive());
                    if(main.getOrderid()!=null&&main.getOrderid()!=""){
                        detail.setOrderId(Integer.valueOf(main.getOrderid()));
                    }
                    detail.setDisplacement(main.getVehiclemain05());
                    detail.setTransmission(main.getVehiclemain06());
                    detail.setConfigure(main.getVehiclemain07());
                    detail.setYearStyle(main.getYearstyle());
                    detail.setAssetsCode(main.getZichancode());
                    detail.setPowerType(main.getDonglitype());
                    detail.setDriver(main.getDriver());
                    detail.setBlowoff(main.getPaifang());
                    detail.setCmsId(main.getCmsid());
                    detail.setCreateTime(fmt.parse(main.getCdate()));
                    detail.setRedBlue(main.getVemain01());
                    detail.setMemo(main.getMemo());
                    detail.setInterior(main.getVemain02());
                    detail.setModelId(main.getModelid());
                    detail.setChe300Style(main.getChe300style());
                    if(main.getChelong()!=null){
                        detail.setCarLength(new BigDecimal(main.getChelong()));
                    }
                    if(main.getWight()!=null){
                        detail.setWight(new BigDecimal(main.getWight()));
                    }
                    if(main.getSeatnum()!=null){
                        detail.setSeatNum(new BigDecimal(main.getSeatnum()));
                    }
                    detail.setCarLevel(main.getCarlevel());
                    detail.setIsParallel(main.getIsparallel());
                    detail.setNeedSync(main.getNeedsync());
                    detail.setIsInternet(main.getIschelianwag());
                    detail.setIsGreen(main.getIsgreen());
                    detail.setCarType(main.getCartype());
                    detail.setCarTypeDetail(main.getCartypedetail());
                    detail.setUpdateBy(main.getUpdateuser());
                    detail.setCreateBy(main.getCreateuser());
                    detail.setUpdateTime(new Date(System.currentTimeMillis()));
                    tsysVehicleDetailService.updateById(detail);

                    String ss= channelIdToCommissionSystem.AssemblyModelData(detail.getName(),detail.getCode());
                    channelIdToCommissionSystem.sendAlterDealerMq(detail.getId().toString(),CommissionConfig.TABLECODE_SSCODE,CommissionConfig.ACTION_EDIT,ss);
                }
            }
        }

}

    @PostMapping("/senderUser")
    @ApiOperation(value = "同步用户id到佣金系统")
    public IResponse senderUser(@RequestBody JSONObject json) {
        String userId =json.getString("userId");
        if(userId==null||userId==""){
            throw  new AfsBaseException("获取用户信息失败！");
        }
        senderChannelToArchive.archivePushMQ(userId, ArchiveConfig.wworguser);
        return new IResponse<>().setMsg("发送成功！");
    }


    @PostMapping("/syncFileToChannel")
    @ApiOperation(value = "同步影像件到渠道服务")
    public IResponse syncFileToChannel(@RequestBody List<ComAttachmentFile> fileList) {
        if(CollectionUtil.isNotEmpty(fileList)){
            comAttachmentFileService.remove(Wrappers.<ComAttachmentFile>query().lambda()
                    .eq(ComAttachmentFile::getBelongNo,fileList.get(0).getBelongNo())
                    .eq(ComAttachmentFile::getBusiNo,fileList.get(0).getBusiNo())
            );
            for (ComAttachmentFile file : fileList){
                file.setId(null);
            }
            comAttachmentFileService.saveBatch(fileList);
        }
        return IResponse.success("同步成功");
    }

    @GetMapping("/syncFileToApply/{fileId}/{belongNo}")
    @ApiOperation(value = "同步影像件到进件服务")
    public IResponse syncFileToApply(@PathVariable String fileId,@PathVariable String belongNo) {

        List<ComAttachmentFile> list = comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                .eq(ComAttachmentFile::getBelongNo, belongNo)
                .eq(ComAttachmentFile::getBusiNo, fileId)
        );
        Map<String, String> headers = new HashMap<>();
        headers.put("clientId", channelConfig.getApplyClientId());
        headers.put("clientSecret", channelConfig.getApplyClientSecret());
        channelUseApplyService.syncFileToApply(list,headers);
        return IResponse.success("成功");
    }

}
